<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 后台通用方法
class Nh extends BaseController {

	public function __construct() {
        parent::__construct();
    }

    public function test_get_student() {
        // 加载类库
        $this->load->library("nonghang");
        // 获取接口数据
        $result = $this->nonghang->get_school_student();
        echo'<pre>';var_export($result);exit;
    }

    // 同步学校数据
    public function update_nh_school($schoolId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('staffModel');
        // 加载类库
        $this->load->library("nonghang");

        $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if($schoolInfo['school_from'] == '') throw new Exception("该学校不是来自系统，数据同步失败");

        // 获取校区,默认更新第一个校区的数据（因为接口还没有返回校区列表）
        $params['schoolId'] = $schoolInfo['id'];
        $params['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($params);
        $campusInfo = $campusList[0];
        // 初始化教师角色：任课教师，班主任，年级管理员，学校管理员
        $this->_update_hzy_teacher_role_data($schoolInfo);
        // // 同步老师数据
        // $this->_update_hzy_teacher_data($schoolInfo);
        // // 同步科目列表
        // $this->_update_hzy_lesson_data($schoolInfo);
        // 同步教室位置接口
        $this->_update_hzy_classroom_data($schoolInfo, $campusInfo);
        // // 同步年级数据接口
        // $this->_update_hzy_grade_data($schoolInfo, $campusInfo);
        // 同步班级接口
        $this->_update_hzy_class_data($schoolInfo, $campusInfo);
        // 同步学生接口
        $this->_update_hzy_student_data($schoolInfo, $campusInfo);


        // 更新时间
        $update['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolTable, $update, "id='{$schoolId}'");
        exit(json("同步数据成功", true));
    }
    // 初始化教师角色数据：任课教师，班主任，年级管理员，学校管理员
    private function _update_hzy_teacher_role_data($schoolInfo) {
        // 获取学校角色数据
        $roleList = $this->staffModel->get_role_list($schoolInfo['id']);
        // 将role_name作为键值
        $roleList = array_value_to_key_with_underline($roleList, 'role_name');
        $insertDataArr = array();
        if(!isset($roleList['任课教师'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '任课教师';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['班主任'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '班主任';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['年级管理员'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '年级管理员';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['学校管理员'])) {
            $saveData['school_id'] = $schoolInfo['id'];
            $saveData['role_name'] = '学校管理员';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '89,90,91,92,93,94,95,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,147,156';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if($insertDataArr) {
            // 插入
            $this->db->insert_batch(StaffModel::$roleTable, $insertDataArr);
        }
    }
    // 同步课室数据
    private function _update_hzy_classroom_data($schoolInfo, $campusInfo) {
        // 获取接口数据
        $result = $this->nonghang->get_school_student();
        // echo'<pre>';var_export($result);exit;
        if(!isset($result['Success']) || $result['Success'] != true) throw new Exception(issset($result['Message']) ? $result['Message'] : '获取人员信息接口失败');
        $apiData = $result['Data'];
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$classroomTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");

        $classroomNameArr = array(); 
        foreach($apiData as $item) {
            if(!in_array($item['department'], $classroomNameArr)) {
                $classroomNameArr[] = $item['department'];
            }
        }

        // var_export($classroomNameArr);exit;

        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolInfo['id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        // $roomList = array_value_to_key($roomList, 'x_classroom_id');
        $roomList = array_value_to_key($roomList, 'classroom_name');
        // 遍历接口所有数据
        $insertRoomBatch = $updateRoomBatch = array();
        foreach($classroomNameArr as $item) {
            // $locationsId = $item['locationID'];
            // if(!$locationsId || $locationsId == 'null') continue;

            $roomData['school_id'] = $schoolInfo['id'];
            // $roomData['x_classroom_id'] = $locationsId;
            $roomData['campus_id'] = $campusInfo['id'];             // 设置校区ID
            // 自己做一个唯一ID
            // $roomData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $locationsId;
            $roomData['classroom_name'] = $item;
            $roomData['is_delete'] = 0;
            $roomData['updatetime'] = date("Y-m-d H:i:s");
            // 更新还是新增
            if(isset($roomList[$item])) {
                $updateRoomBatch[] = $roomData;
            } else {
                $roomData['createtime'] = $roomData['updatetime'];
                $insertRoomBatch[] = $roomData;
            }
        }
        if(count($insertRoomBatch)) $this->db->insert_batch(ClassesModel::$classroomTable, $insertRoomBatch);
        if(count($updateRoomBatch)) $this->db->update_batch(ClassesModel::$classroomTable, $updateRoomBatch, "classroom_name");
    }
    // 同步班级接口
    private function _update_hzy_class_data($schoolInfo, $campusInfo) {
        // 获取接口数据
        $result = $this->nonghang->get_school_student();
        // echo'<pre>';var_export($result);exit;
        if(!isset($result['Success']) || $result['Success'] != true) throw new Exception(issset($result['Message']) ? $result['Message'] : '获取人员信息接口失败');

        $apiData = $result['Data'];

        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        // 排除‘功能课室’班级即‘x_class_id’为空
        $this->db->update(ClassesModel::$classTable, $deleteState, "`school_id`='{$schoolInfo['id']}' AND `x_class_id` != ''");
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolInfo['id'];
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        if(empty($gradeList)) {
            // throw new Exception('请先创建一个年级');
            $this->db->insert(ClassesModel::$gradeTable, array(
                'school_id' => $schoolInfo['id'],
                'x_grade_id' => 0,
                'campus_id' => $campusInfo['id'],        // 设置校区id
                'x_unique_id' => 0,
                'grade_name' => '默认年级',
                'is_delete' => 0,
                'createtime' => date("Y-m-d H:i:s"),
                'updatetime' => date("Y-m-d H:i:s")
            ));
        }
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeInfo = $gradeList[0];
        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolInfo['id'];
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'classroom_name');
        // 获取本校全部班级,排除功能课室班级，避免清除掉了课室
        $classParams['schoolId'] = $schoolInfo['id'];
        $classParams['inFunctional'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        //获取全部行政班信息接口
        $insertClassBatch = $updateClassBatch = array();
      
        $classNameArr = array(); 
        foreach($apiData as $item) {
            if(!in_array($item['department'], $classNameArr)) {
                $classNameArr[] = $item['department'];
            }
        }
        foreach($classNameArr as $item) {
            $classData['school_id'] = $schoolInfo['id'];
            $classData['campus_id'] = $campusInfo['id']; // 设置校区id
            $classData['grade_id'] = $gradeInfo['id'];
            // $classData['x_class_id'] = $item['qualifiedClassID'];
            // 自己做一个唯一ID
            // $classData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $item['qualifiedClassID'];
            $classData['classroom_id'] = isset($roomList[$item]) ? $roomList[$item]['id'] : 0;
            $classData['class_name'] = $item;
            $classData['class_type'] = CLASSES_TYPE_NORMAL;
            $classData['is_delete'] = 0;
            $classData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($classList[$item])) {
                $updateClassBatch[] = $classData;
            } else {
                $classData['createtime'] = $classData['updatetime'];
                $insertClassBatch[] = $classData;
            }
        }
     
        // echo '<pre>';var_export($insertClassBatch);exit;
        if(count($insertClassBatch)) $this->db->insert_batch(ClassesModel::$classTable, $insertClassBatch);
        if(count($updateClassBatch)) $this->db->update_batch(ClassesModel::$classTable, $updateClassBatch, "class_name");
    }
    // 同步学生接口
    private function _update_hzy_student_data($schoolInfo, $campusInfo){
        // 获取接口数据
        $result = $this->nonghang->get_school_student();
        // echo'<pre>';var_export($result);exit;
        if(!isset($result['Success']) || $result['Success'] != true) throw new Exception(issset($result['Message']) ? $result['Message'] : '获取人员信息接口失败');

        $apiData = $result['Data'];
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $deleteState['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolStudentTable, $deleteState, "`school_id`='{$schoolInfo['id']}'");
        
        // 获取本校全部学生
        $studentParams['schoolId'] = $schoolInfo['id'];
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'x_student_id');
        // 获取行政班
        $classParams['schoolId'] = $schoolInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        // 获取接口学生
        $insertStudentBatch = $updateStudentBatch = array();
        // $apiData = $result['result']['studentInfos'];
        $defaultPwd = password_hash(123456, PASSWORD_DEFAULT);
        foreach($apiData as $item) {
            $studentData['is_delete'] = 0;
            $studentData['school_id'] = $schoolInfo['id'];
            $studentData['campus_id'] = $campusInfo['id'];      // 设置校区ID
            $studentData['x_student_id'] = $item['id'];
            // 增加username,跟x_student_id一样
            $studentData['username'] = $item['id'];
            // 将的物理卡号设置跟x_student_id一样
            // $studentData['realcard'] = $item['card_id'];

            $studentData['realcard'] = $item['using_cardnum'];
            // 身份证号
            $studentData['shenfenzheng'] = $item['idcard'];

            // 自己做一个唯一ID
            $studentData['x_unique_id'] = $schoolInfo['id']. "_". $campusInfo['id']. "_". $item['id'];

            if(!isset($classList[$item['department']])) {
                throw new Exception('学生所属班级：' . $item['department'] . ' 不存在');
                // continue;
            }

            $studentData['class_id'] = $classList[$item['department']]['id'];
            $studentData['realname'] = $item['user_name'];
            $studentData['gender'] = $item['sex'] ? $item['sex'] : '男';
            
            $studentData['updatetime'] = date("Y-m-d H:i:s");

            if(isset($studentList[$item['id']])) {
                $updateStudentBatch[] = $studentData;
            } else {
                $studentData['password'] = $defaultPwd;
                $studentData['createtime'] = $studentData['updatetime'];

                $studentData['headimgurl'] = $item['sex'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg');
                
                $insertStudentBatch[] = $studentData;
            }
        }
        if(count($insertStudentBatch)) $this->db->insert_batch(SchoolModel::$schoolStudentTable, $insertStudentBatch);
        if(count($updateStudentBatch)) $this->db->update_batch(SchoolModel::$schoolStudentTable, $updateStudentBatch, "x_unique_id");
    }

    // 单点登录
    

}